package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String dishKey = "dishKey:" + dishDto.getCategoryId();
        redisTemplate.delete(dishKey);
        return R.success("\"新增菜品成功\"");
    }

    /**
     * 分页查询菜品
     */
    @GetMapping("page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        //创建分页构造器对象
        Page<Dish> pageInfo1 = new Page<>(page, pageSize);
        //创建条件对象
        QueryWrapper<Dish> queryWrap = new QueryWrapper<>();
        queryWrap.like(StringUtils.isNotBlank(name), "name", name).orderByAsc("sort").orderByDesc("update_time");
        //执行分页查询
        dishService.page(pageInfo1, queryWrap);

        //创建DishDto分页构造器
        Page<DishDto> pageInfo2 = new Page<>(page, pageSize);
        //拷贝除records数据以外的所有属性
        BeanUtils.copyProperties(pageInfo1, pageInfo2, "records");
        //创建DishDto集合
        List<DishDto> dishDtoList = new ArrayList<>();
        //遍历pageInfo1getRecords，获取里面的每一个Records
        for (Dish dish : pageInfo1.getRecords()) {
            DishDto dishDto = new DishDto();
            //把dish的Records属性拷贝给dishDto
            BeanUtils.copyProperties(dish, dishDto);
            //TODO 处理分类名称
            Category category = categoryService.getById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        pageInfo2.setRecords(dishDtoList);
        return R.success(pageInfo2);
    }

    /**
     * 查询修改的菜品
     */
    @GetMapping("{id}")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    public R updateWithFlavor(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        Set keys = redisTemplate.keys("dishKey:*");
        redisTemplate.delete(keys);
        return R.success("添加成功");
    }

    /**
     * 查询套餐对应的菜品
     */
    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishList = (List<DishDto>) redisTemplate.opsForValue().get("dishKey:" + dish.getCategoryId());
        if (dishList != null) {
            return R.success(dishList);
        }
        //构造Dish查询条件
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, "category_id", dish.getCategoryId())
                .orderByAsc("sort")
                .orderByDesc("update_time");
        //查询Dish列表
        List<Dish> list = dishService.list(queryWrapper);

        //创建DishDto集合以便存取数据
        List<DishDto> dishDtoList = new ArrayList<>();

        //遍历Dish集合，分别赋值给DishDto
        for (Dish dish1 : list) {
            //创建dishDto封装dish和flavor数据
            DishDto dishDto = new DishDto();
            //封装Dish数据给DishDto
            BeanUtils.copyProperties(dish1, dishDto);
            //根据菜品id查询对应的口味集合

            QueryWrapper<DishFlavor> flavorQueryWrapper = new QueryWrapper<>();
            flavorQueryWrapper.eq("dish_id", dishDto.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(flavorQueryWrapper);
            //把口味集合封装给dishDto
            dishDto.setFlavors(dishFlavors);
            //把dishDto添加入dishDto集合中
            dishDtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set("dishKey:" + dish.getCategoryId(), dishDtoList, 30, TimeUnit.SECONDS);
        return R.success(dishDtoList);
    }
}
